
define(
	[
		'require',
		'./agreement_ctrl'
	],
	function(require){
		var Controller = Ember.Controller.extend({

			needs: ["configAgreement"],

			// currentIp: Ember.computed.alias('controllers.configAgreement.currentIp'),

			init: function(){
				this._super();
			},
			form : {
				policys:"DROP",
				glopolicy:"DROP",
				sourceIp:"",
				sourceIp1:"",
				sourcePort : "",
				sourcePort1 : "",
				ip : "",
				ip1 : "",
				port : "",
				port1 : "",
				mac : "",
				policyName:"",
				confType:"4"
			},
			formTopArray: Ember.A([{"name":"Top10","id":"10"},{"name":"Top50","id":"50"},{"name":"Top100","id":"100"}]),
			formTopValue:'',
			defaultpolicys : Ember.A([{
				"displaytext" : "全部接收",
				"value" : "ACCEPT"
			}, {
				"displaytext" : "全部丢弃",
				"value" : "DROP"
			} ]),

			policyRules: Ember.A(),

			currentIp: function(){
				var ctrl = this;
				return ctrl.store.ajax("GET","analyzers/"+ctrl.get("model.id")+"/info").then(function(response){
					var analyzer = response.analyzer;
					ctrl.set("analyzerIp",analyzer.ip)
				});
			},

			checkedAll: Ember.computed('policyRules.@each.checked', function(key, value) {
				var policyRules = this.get('policyRules');

				if (arguments.length > 1) {
					policyRules.forEach(function(item) {
						item.set('checked', value);
					});
				} else {
					return policyRules.filterProperty('checked', true).length == policyRules.length;
				}
			}),

			noneRulesChecked: Ember.computed('policyRules.@each.checked', function(key, value) {
				return this.get('policyRules').filterProperty('checked', true).length == 0;
			}),

			initConfData: function(){
				var ctrl = this;
				ctrl.store.ajax("GET", "analyzers/"+ctrl.get("model.id")+"/filters",{
					configItem:"filter"
				}).then(function(response) {
	
					var result = response.result;
					var dict = {"DROP": "全部丢弃", "ACCEPT": "全部接收"}
					result.forEach(function(node){

						if(node.policys == "DROP"){
							Ember.set(node,"policyName","全部丢弃")
						}else{
							Ember.set(node,"policyName","全部接收")
						}
					});
					
					ctrl.set("policyRules", Ember.A(result));
					// var configobj = response.configData;
					// if (configobj) {
					// 	if (configobj.filter_default_policy) {
					// 		ctrl.set("form.glopolicy",configobj.filter_default_policy);
					// 	}
					// 	if (configobj.filter_rules) {
					// 		var rules = JSON.parse(configobj.filter_rules);
					// 		var dict = {"DROP": "全部丢弃", "ACCEPT": "全部接收"};
					// 		for (var k = 0; k<rules.length; k++) {
					// 			var policyCode=rules[k].policys;
					// 			if(dict[policyCode]){
					// 				rules[k].policyName=dict[policyCode];
					// 			}
					// 			rules[k].id=k+1;
					// 			rules[k] = Ember.A(rules[k]);
					// 		}
					// 		console.log(rules);
					// 		ctrl.set("policyRules", Ember.A(rules));
					// 	}
					// }	
				});
			},
			
			checkFormValid: function(){
				var form = this.get("form");
				
				this.set("formTip", null);
				this.set("saveResult", null);
				var ipReg1 =/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;

				if(form.sourceIp){
					if(!ipReg1.test(form.sourceIp)){  
					   this.set("saveResult", "开始源IP地址范围非法，请重新输入!");
					   return false;
					}  
				}
				if(form.sourceIp1){
					if(!ipReg1.test(form.sourceIp1)){  
					   this.set("saveResult", "结束源IP地址范围非法，请重新输入!");
					   return false;
					}  
				}
				if(form.sourcePort){
					var reg = new RegExp("^[0-9]*$"); 
					var port=form.sourcePort;
					var port1=parseInt(form.sourcePort);
					if (!(reg.test(port) && port1<65536)) {
						this.set("saveResult", "开始源端口错误，请重新输入!");
						return false;
					} 
				}
				if(form.sourcePort1){
					var reg = new RegExp("^[0-9]*$"); 
					var port1=form.sourcePort1;
					var port=parseInt(form.sourcePort1);
					if (!(reg.test(port1) && port<65536)) { 
						this.set("saveResult", "结束源端口错误，请重新输入!");
						return false;
					} 
				}

				if(form.ip){
					if(!ipReg1.test(form.ip)){  
					   this.set("saveResult", "开始目的IP地址范围非法，请重新输入!");
					   return false;
					}  
				}
				if(form.ip1){
					if(!ipReg1.test(form.ip1)){  
					   this.set("saveResult", "结束目的IP地址范围非法，请重新输入!");
					   return false;
					}  
				}
				if(form.port){
					var reg = new RegExp("^[0-9]*$"); 
					var port=form.port;
					var port1=parseInt(form.port);
					if (!(reg.test(port) && port1<65536)) {
						this.set("saveResult", "开始目的端口错误，请重新输入!");
						return false;
					} 
				}
				if(form.port1){
					var reg = new RegExp("^[0-9]*$"); 
					var port1=form.port1;
					var port=parseInt(form.port1);
					if (!(reg.test(port1) && port<65536)) { 
						this.set("saveResult", "结束目的端口错误，请重新输入!");
						return false;
					} 
				}
				if(form.mac){
					var reg2=/[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}/;
					var reg3=/[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}/;
					if(!(reg2.test(form.mac) || reg3.test(form.mac))){  
						   this.set("saveResult", "Mac地址非法，请重新输入!");
						   return false;
					} 
				}
				
				if((form.ip && form.ip1) || (form.sourceIp1 && form.sourceIp)){
					var startIp=form.ip;
					var endIp=form.ip1;
					var startIp1=form.sourceIp;
					var endIp1=form.sourceIp1;
					if(startIp){
						var startIpint=parseInt(startIp.replace(/\d+\.?/ig,function(a){
							a = parseInt(a); 
							return (a > 15 ? "" : "0") + a.toString(16);
						}),16);
					};
					if(endIp){
						var endIpint=parseInt(endIp.replace(/\d+\.?/ig,function(b){
							b = parseInt(b); 
							return (b > 15 ? "" : "0") + b.toString(16);
						}),16);
					};
					if(startIp1){
						var startIpint1=parseInt(startIp1.replace(/\d+\.?/ig,function(a){
							a = parseInt(a); 
							return (a > 15 ? "" : "0") + a.toString(16);
						}),16);
					}
					if(endIp1){
						var endIpint1=parseInt(endIp1.replace(/\d+\.?/ig,function(b){
							b = parseInt(b); 
							return (b > 15 ? "" : "0") + b.toString(16);
						}),16);
					}
					if(startIpint && endIpint){
						if(startIpint>endIpint){
							 this.set("saveResult", "开始目的IP地址不应大于结束目的IP地址!");
								return false;
						}
					}
					if(startIpint && endIpint){
						if(startIpint == endIpint){
							 this.set("saveResult", "开始目的IP地址与结束目的IP地址相同!");
								return false;
						}
					}
					if(startIpint1 && endIpint1){
						if(startIpint1>endIpint1){
							 this.set("saveResult", "开始源IP地址不应大于结束源IP地址!");
								return false;
						}
					}
					if(startIpint1 && endIpint1){
						if(startIpint1 == endIpint1){
							 this.set("saveResult", "开始源IP地址与结束源IP地址相同!");
								return false;
						}
					}
				}
				
				if((form.port && form.port1) || (form.sourcePort && form.sourcePort1)){
					var startPort=parseInt(form.port);
					var endPort=parseInt(form.port1);
					var startPort1=parseInt(form.sourcePort);
					var endPort1=parseInt(form.sourcePort1);
					if(startPort>endPort){
						 this.set("saveResult", "开始目的端口不应大于结束目的端口!");
							return false;
					}
					if(startPort == endPort){
						 this.set("saveResult", "开始目的端口与结束目的端口相同!");
							return false;
					}
					if(startPort1>endPort1){
						 this.set("saveResult", "开始源端口不应大于目的结束源端口!");
							return false;
					}
					if(startPort1 == endPort1){
						 this.set("saveResult", "开始源端口与结束源端口相同!");
							return false;
					}
					
				}
				
				if(!(form.ip||form.port||form.mac||form.sourcePort||form.sourceIp)){
					this.set("saveResult", "不能添加空策略!");
					return false;
				}
				this.set("saveResult", null);
				return true;
			},

			actions : {
				reset : function() {
					this.set("formTip", null);
					this.set("saveResult", null);
				},
				
				addPolicy : function() {
					if (!this.checkFormValid()) {
						return;
					}
					var policyRules = this.get("policyRules");
					var policyObj = {};
					var ctrl = this;
					var form = this.get("form");
					var ipstr="";
					var ip1str="";
					if (form.ip&&form.ip1) {
						 ipstr=form.ip+"-"+form.ip1;
					} else {
						if (form.ip) {
							 ipstr=form.ip;
						}

						if (form.ip1) {
							 ipstr=form.ip1;
						}
					};
					if (form.sourceIp&&form.sourceIp1) {
						 ip1str=form.sourceIp+"-"+form.sourceIp1;
					} else {
						if (form.sourceIp) {
							 ip1str=form.sourceIp;
						}

						if (form.sourceIp1) {
							 ips1tr=form.sourceIp1;
						}
					};
					var portstr="";
					if (form.port&&form.port1) {
						 portstr=form.port+"-"+form.port1;
					} else {
						if(form.port){
							 portstr=form.port;
						};
						if(form.port1){
							 portstr=form.port1;
						}
					}
					var port1str="";
					if (form.sourcePort&&form.sourcePort1) {
						 port1str=form.sourcePort+"-"+form.sourcePort1;
					} else {
						if(form.sourcePort){
							 port1str=form.sourcePort;
						};
						if(form.sourcePort1){
							 port1str=form.sourcePort1;
						}
					}
					var addId=1+policyRules.length;
					var dict = {"DROP": "全部丢弃","ACCEPT": "全部接收"};
					policyObj.dIp = ipstr;
					policyObj.sIp = ip1str;
					policyObj.id=addId;
					policyObj.dPort = portstr;
					policyObj.sPort = port1str;
					policyObj.mac = form.mac;
					policyObj.policys=form.policys;
					if(dict[policyObj.policys]){
						policyObj.policyName=dict[policyObj.policys];
					}
					policyRules.pushObject(Ember.A(policyObj));
					ctrl.send("closeDialog");
					this.set("form.ip", null);
					this.set("form.ip1", null);
					this.set("form.port", null);
					this.set("form.port1", null);
					this.set("form.sourceIp", null);
					this.set("form.sourceIp1", null);
					this.set("form.sourcePort", null);
					this.set("form.sourcePort1", null);
					this.set("form.mac", null);
					this.set("policyName",null);
					this.set("form.policys", "ACCEPT");
				},

				delPolicy : function() {
					var policyRules = this.get('policyRules');
					var checked = policyRules.filterProperty('checked', true);
					if (checked.length == 0) {
						alertDialog("请勾选要删除的策略!");
					}
					confirmDialog("确定删除所选过滤策略吗?").then(function(){
						policyRules.removeObjects(checked);
					});
				},

				singleDelPolicy : function(policyRule) {
					var policyRules = this.get('policyRules');	
					confirmDialog("确定删除该过滤策略吗?").then(function(){
						policyRules.removeObject(policyRule);
					});		
				},

				upPriority: function(policyRule){
					var policyRules = this.get("policyRules"),
						index = policyRules.indexOf(policyRule);

					if(index != -1 && index > 0){
						policyRules.removeObject(policyRule);
						policyRules.insertAt(index-1, policyRule);
					}
				},

				downPriority: function(policyRule){
					var policyRules = this.get("policyRules"),
						len = policyRules.length,
						index = policyRules.indexOf(policyRule);

					if(index != -1 && len > 1 && index < len-1 ){
						policyRules.removeObject(policyRule);
						policyRules.insertAt(index+1, policyRule);
					}
				},

				//对话框操作打开方法
				openDialog: function(){
					this.set("formTip", null);
					this.set("saveResult", null);
					this.set("form.policys", "ACCEPT");
					var dialog = Broada.getView("packet_filter_add");
					dialog.openDialog();
				},

				//对话框操作打开方法
				updOpenDialog: function(policyRule){
					this.set("formTip", null);
					this.set("saveResult", null);
					var ip=policyRule.ip;
					var port=policyRule.port;
					var ip1=null;
					var ip2=null;
					var port1=null;
					var port2=null;
					if(ip && (ip.indexOf("-") !=-1)){
						var ipIndex=ip.indexOf("-");
						ip1=ip.substr(0,ipIndex);
						ip2=ip.substr(ipIndex+1,ip.length);
					}else{
						ip1=ip;
					}
					if(port && (port.indexOf("-") !=-1)){
						var portIndex=port.indexOf("-");
						port1=port.substr(0,portIndex);
						port2=port.substr(portIndex+1,port.length);
					}else{
						port1=port;
					}
					this.set("id",policyRule.id);
					this.set("form.ip", ip1);
					this.set("form.ip1", ip2);
					this.set("form.port", port1);
					this.set("form.port1", port2);
					this.set("form.mac", policyRule.mac);
					this.set("form.policys", policyRule.policys);
					var dialog = Broada.getView("packet_filter_upd");
					dialog.openDialog();
				},

				updCloseDialog: function(){
					this.set("formTip", null);
					this.set("saveResult", null);
					this.set("form.ip", null);
					this.set("form.ip1", null);
					this.set("form.port", null);
					this.set("form.port1", null);
					this.set("form.sourceIp", null);
					this.set("form.sourceIp1", null);
					this.set("form.sourcePort", null);
					this.set("form.sourcePort1", null);
					this.set("form.mac", null);
					this.set("id",null);
					this.set("form.policyName",null);
					this.set("form.policys","DROP");
					Broada.getView("packet_filter_upd").closeDialog();
				},

				updPolicy : function() {
					if (!this.checkFormValid()) {
						return;
					}
					var policyRules = this.get("policyRules");
					var policyObj = {};
					var ctrl = this;
					var form = ctrl.get("form");
					var updObjId=ctrl.get("id");		

					var dict = {"DROP": "全部丢弃", "ACCEPT": "全部接收"};	
					if(dict[form.policys]){
						this.set("form.policyName",dict[form.policys]);
					}

					ctrl.set("form.ip", Ember.EnumerableUtils.filter([form.ip, form.ip1], function(v) {return !!v;}).join('-'));
					ctrl.set("form.port", Ember.EnumerableUtils.filter([form.port, form.port1], function(v) {return !!v;}).join('-'));

					if(updObjId){
						policyRules.findBy('id', updObjId).setProperties(form);
					}
					ctrl.send("updCloseDialog");
					ctrl.set("form.ip", null);
					ctrl.set("form.ip1", null);
					ctrl.set("form.port", null);
					ctrl.set("form.port1", null);
					ctrl.set("form.mac", null);
					ctrl.set("id",null);
					ctrl.set("form.policyName",null);
					ctrl.set("form.policys","DROP");
				},

				closeDialog: function(){
					this.set("saveResult", null);
					Broada.getView("packet_filter_add").closeDialog();
				},

				queryPolicys:function(){
					var ctrl = this;
					ctrl.store.ajax("GET", "configs/systemConfig",{
					configItem:"filter"
					}).then(function(response) {
						var configobj = response.configData;
						if (configobj) {
							if (configobj.filter_default_policy) {
								ctrl.set("form.glopolicy",configobj.filter_default_policy);
							}
							if (configobj.filter_rules) {
								var rules = JSON.parse(configobj.filter_rules);
								for (var k = 0; k<rules.length; k++) {
									rules[k].id=k+1;
									rules[k] = Ember.A(rules[k]);
								}
								ctrl.set("policyRules", Ember.A(rules));
							}
						}	
					});
				},
				
				save : function() {
					var ctrl = this,
						form = this.get("form"),
						policyRules = this.get('policyRules'),
						rulesArray = [];
					
					ctrl.set("saveResult", null);
					policyRules.forEach(function(item) {
						console.log(item);
						rulesArray.push({'sIp':item["sIp"],'sPort':item["sPort"],'dIp':item["dIp"],'dPort':item["dPort"],'policys':item["policys"]});
					});
					this.store.ajax("POST", "analyzers/filters/"+ctrl.get("model.id"), {
						defaultpolicy : form.glopolicy,
						policyRules:JSON.stringify(rulesArray),
						confType:form.confType
					}).then(function(response){
						alertTip("保存成功！");
					});
				}
			}
		});


		APM.ConfigPacketfilterfacePacketfilterController = Controller;

		return Controller;
	}
);